package com.oocl.batchdatav2.scanner.impl;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.oocl.batchdatav2.pojo.Customer;
import com.oocl.batchdatav2.scanner.DataScanner;
import com.oocl.batchdatav2.util.StringValidator;

public class DataScannerImpl implements DataScanner {
	
	private Scanner scanner;
	
	public DataScannerImpl(InputStream in) {
		scanner = new Scanner(in);
	}

	@Override
	public List<Customer> getCustomersFromStream() {
		List<Customer> result = new ArrayList<>();
		for (String line : getAllLines()) {
			String[] infos = line.trim().split("\\s+");
			try {
				Customer customer = new Customer();
				customer.setId(Integer.parseInt(infos[0]));
				customer.setName(infos[1]);
				customer.setEmail(infos[2]);
				customer.setSex(Boolean.valueOf(infos[3]));
				customer.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(infos[4]));
				result.add(customer);
			} catch (NumberFormatException | ParseException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	private List<String> getAllLines() {
		List<String> result = new ArrayList<>();
		
		while (scanner.hasNextLine()) {
			String line = scanner.nextLine();
			if (StringValidator.validateLine(line)) {
				result.add(line);
			}
		}
		return result;
	}

}
